package com.lj.framework.web.service;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lj.common.constant.BaseConstant;
import com.lj.common.core.model.system.SysUser;
import com.lj.common.core.model.vo.LoginUser;
import com.lj.common.core.redis.RedisCache;
import com.lj.common.enums.log.LoginStatusEnum;
import com.lj.common.exception.ServiceException;
import com.lj.common.exception.user.CaptchaException;
import com.lj.common.exception.user.CaptchaExpireException;
import com.lj.common.exception.user.UserPasswordNotMatchException;
import com.lj.common.utils.MessageUtil;
import com.lj.common.utils.ServletUtil;
import com.lj.common.utils.ip.IpUtil;
import com.lj.framework.manager.AsyncManager;
import com.lj.framework.manager.factory.AsyncFactory;
import com.lj.system.service.ISysConfigService;
import com.lj.system.service.ISysUserService;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 系统登录服务类
 *
 * @author 小李飞刀
 */
@Service
public class SysLoginService {

    @Resource
    private ISysConfigService configService;

    @Resource
    private RedisCache<String, String> redisCache;

    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private ISysUserService userService;

    @Resource
    private TokenService tokenService;


    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid) {
        boolean captchaOnOff = configService.selectCaptchaOnOff();
        // 验证码开关-如果开启验证码校验
        if (captchaOnOff) {
            validateCaptcha(username, code, uuid);
        }
        // 用户验证
        Authentication authentication;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLoginInfo(username, LoginStatusEnum.LOGIN_FAIL.name(), MessageUtil.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLoginInfo(username, LoginStatusEnum.LOGIN_FAIL.name(), e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLoginInfo(username, LoginStatusEnum.LOGIN_SUCCESS.name(), MessageUtil.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId) {
        UpdateWrapper<SysUser> updateWrapper = Wrappers.update();
        updateWrapper.set("login_ip", IpUtil.getIpAddr(ServletUtil.getRequest())).set("login_date", DateUtil.date())
                .eq("user_id", userId);
        userService.update(updateWrapper);
    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     */
    public void validateCaptcha(String username, String code, String uuid) {
        String verifyKey = BaseConstant.CAPTCHA_CODE_KEY + uuid;
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null) {
            AsyncManager.me().execute(AsyncFactory.recordLoginInfo(username, LoginStatusEnum.LOGIN_FAIL.name(), MessageUtil.message("user.captcha.expire")));
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha)) {
            AsyncManager.me().execute(AsyncFactory.recordLoginInfo(username, LoginStatusEnum.LOGIN_FAIL.name(), MessageUtil.message("user.captcha.error")));
            throw new CaptchaException();
        }
    }

}
